package leetcode;

public class FindFirstLastPositionElementSortedArray {

    public static void main(String[] args) {
        FindFirstLastPositionElementSortedArray findFirstLastPositionElementSortedArray = new FindFirstLastPositionElementSortedArray();
        int[] search = findFirstLastPositionElementSortedArray.searchRange(new int[]{5,7,7,8,8,10}, 8);
        System.out.println(search[0]);
        System.out.println(search[1]);
    }

    public int[] searchRange(int[] nums, int target) {
        int []res = new int[2];
        int search = search(nums, target);
        if(search == -1) return new int[]{-1, -1};
        while (search >= 0 && nums[search] == target){
            search-- ;
        }
        res[0] = search + 1;
        int ri = search + 1;
        while (ri < nums.length && nums[ri] == target){
            ri ++;
        }
        res[1] = ri - 1;
        return res;
    }


    public int search(int[] nums, int target) {
        int l = 0, r = nums.length, middle = 0;
        if (r == 0) {
            return -1;
        }
        if (r == 1) {
            return nums[0] == target ? 0 : -1;
        }

        r --;

        while (l <= r){
            middle = (l + r) / 2;
            if(nums[middle] == target) return middle;
            if(nums[0] <= nums[middle]){
                if(target >= nums[0] && target < nums[middle]){
                    r = middle - 1;
                }else{
                    l = middle + 1;
                }
            }else{
                if(target > nums[middle] && target <= nums[nums.length - 1]){
                    l = middle + 1;
                }else{
                    r = middle -1;
                }
            }
        }
        return -1;
    }

}
